#coding=utf-8

from django.shortcuts import render_to_response
from django.template import RequestContext
from DjangoBbs.BbsTheme import models_vote

from DjangoBbs.Common import Permission
from DjangoBbs.Help.VisitPerm import VisitBbsClass
from PublicTool import HttpWrite
from PublicTool.ViewHelper import ViewHelper
import models
import forms
__author__ = 'czq'

def get_Class_List():
    return models.BbsClass.objects.filter(isHidden=False)

from common import ThemeViewHelper, addReply_Extcredit, addTheme_Extcredit


class ClassView(ViewHelper):
    def __init__(self):
        self.moduleName='BbsTheme'
        self.typeName='class'
    def get_model(self):
        return models.BbsClass

    def list_get_list(self,request):
        list=get_Class_List()
        if self.classId==None:
            self.bbsClass=None
            return list.filter(parent=None).order_by('rank')
        else:
            #获取当前板块
            self.bbsClass=models.BbsClass.objects.get(id=self.classId)
            #返回子板块
            return list.filter(parent=self.bbsClass)
    def list_get_dict(self,request):

        return {'bbsClass':self.bbsClass}
    def list(self,request,classId=None):
        self.classId=classId

        return super(ClassView,self).list(request)

def get_Theme_list():
    return models.BbsTheme.objects.filter(isDel=False)
class ThemeView(ThemeViewHelper):
    def __init__(self):
        self.moduleName='BbsTheme'
        self.typeName='theme'
    def get_model(self):
        return models.BbsTheme

    #列表
    def list_get_list(self,request):
        #self.bbsClass=models.BbsClass.objects.get(id=self.classId)
        from DjangoBbs.Common.Theme_Filter import Theme_Filter_Rank
        list = Theme_Filter_Rank(request,self.bbsClass)
        #raise Exception,list
        return list
        #全部主题

    def list_get_dict(self,request):
        dict={}
        if self.bbsClass:
            #获取子板块
            classChild=get_Class_List().filter(parent=self.bbsClass)
            adminUsers=self.bbsClass.adminUsers.all()#版主
            #raise Exception,len(adminUsers)
            dict.update({'instance':self.bbsClass,'classChild':classChild,'adminUsers':adminUsers})
        return dict
    def list(self,request,classId=None):
        self.classId=classId
        self.bbsClass=models.BbsClass.objects.get(id=self.classId)
        if not VisitBbsClass(request.user,self.bbsClass):
            return HttpWrite.infoFailure(request,'错误的板块')
        #if self.bbsClass.visitPerm!=None:
        #
        #    if self.bbsClass.visitPerm.allowUsers.all()!=[]:
        #        pass
        #        raise Exception,self.bbsClass.visitPerm.allowUsers.all()
            #raise Exception,1
        return super(ThemeView,self).list(request)

    def list_search(self,request):
        dict={}
        dict['value']=request.GET.get('value','')
        dict['uid']=request.GET.get('uid','')
        dict['BbsClassSelectForm']=forms.BbsClassSelectForm(
            initial={'bbsClass': request.GET.get('bbsClass','')}
        )

        return render_to_response("BbsTheme/theme_list_search.html",dict,context_instance=RequestContext(request))


    def action_instance_change(self,request,instance,attr,value=True):
                    bool=eval("instance.%s==%s"%(attr,value))
                    if bool:
                        return HttpWrite.infoFailure("重复设置！")
                    else:
                        c = compile("instance.%s=%s"%(attr,value),'','exec')
                        exec c
                        from DjangoBbs.Help import helpers
                        helpers.SystemLog_Add(request,moduleName=u'主题',remark=attr+value,outId=instance.id)
                    instance.save()
                    return super(ThemeView,self).showUrlReverse("bbsTheme_show",args=(instance.id,))
    #管理主题
    def show_acton(self,request,id):
        if request.method=="POST":
            action=request.POST.get("action",'')
            if action!="":
                value=request.POST.get('action_value',True)
                        #exec ("%s=%s"%(attr,flag))#attr==flag

                instance=self.get_model().objects.get(id=id)
                #判断权限
                isManager=Permission.isClassManager(request,instance.classId)
                if not isManager:
                    return HttpWrite.infoSuccess(u'你没有权限操作')
                if action=="del":
                    #raise Exception,instance
                    if instance.classId.lastTheme!=instance:
                        pass
                    else:
                        instance.classId.lastTheme=None
                        instance.classId.save()
                    #instance.delete()
                    instance.isDel=True
                    instance.save()
                    #删除积分
                    addTheme_Extcredit(request,instance.addUser,'del')

                    return super(ThemeView,self).showUrlReverse("bbsTheme_list",args=(instance.classId.id,))
                else:
                    return self.action_instance_change(request,instance,action,value=value)

        return super(ThemeView,self).showUrlReverse("bbsTheme_show",args=(id,))

    def show_vote(self,request,id):
        instance=self.get_model().objects.get(id=id)
        if request.method=="POST":
            value=request.POST.get("voteValue",'')
            if value!='':
                #raise Exception,value
                from models_vote import BbsThemeVote,BbsThemeVoteRecord,BbsThemeVoteAttr

                isVote = BbsThemeVoteRecord.objects.filter(theme=instance,addUser=request.user)[:1]
                if isVote:
                    pass
                else:
                    #总票数
                    attr=BbsThemeVoteAttr.objects.get(theme=instance)
                    attr.totalCount+=1
                    attr.save()

                    #票数+1
                    vote = BbsThemeVote.objects.get(id=value)
                    vote.voteCount+=1
                    vote.save()

                    #记录投票
                    record=BbsThemeVoteRecord(theme=instance,addUser=request.user)
                    record.save()

        return super(ThemeView,self).showUrlReverse("bbsTheme_show",args=(id,))

    def add_get_form(self,request):
        return forms.BbsThemeForm
    def add_add_get_form(self,request,**kwargs):
        return super(ThemeView,self).add_add_get_form(request,classId=self.classModel)
    def add_save_prev(self,request,instance,change):
        instance.addUser=request.user
        instance.classId=self.classModel
        if self.vote=='True':
            instance.isVote=True
        return True
    def add_save_next(self,request,instance,change):
        if self.vote=='True':
            formset=self.voteAttrForm(request.POST,instance=instance)
            if formset.is_valid():
                formset.save()
            formset = self.voteForm(request.POST,instance=instance)
            if formset.is_valid():
                formset.save()
        instance.classId.themeCount+=1
        instance.classId.save()
        #raise Exception,self.voteForm
        #formset = self.voteForm(request.POST, instance=instance)
        #if formset.is_valid():
        #    formset.save()
    def add_response_succeed(self,request,dict,instance):
        #积分
        super(ThemeView,self).addTheme_Extcredit(request)
        return super(ThemeView,self).showUrlReverse('bbsTheme_show',args=(instance.id,))
    def add_get_dict(self,request):
        dict={}
        self.vote=request.GET.get('vote','False')
        dict['vote']=self.vote
        if self.vote=='True':
            self.voteForm=forms.inlineformset_factory(models.BbsTheme, models_vote.BbsThemeVote,form=forms.BbsThemeVoteForm,extra=5)
            dict['voteForm']=self.voteForm
            self.voteAttrForm=forms.BbsThemeVoteAttrFormSet
            dict['voteAttrForm']=self.voteAttrForm
        dict['classModel']=self.classModel
        return dict

    #发布主题
    def add(self,request,id='0'):
        classId=request.GET.get('classId','')
        if classId!='':
            self.classModel=models.BbsClass.objects.get(id=classId)
            if not VisitBbsClass(request.user,self.classModel):
                return HttpWrite.infoFailure(request,'错误的板块')

            #if self.classModel.typeId.code=='travel':
            #    return super(ThemeView,self).showUrl('/Travel/RideLine_add/?classId='+classId)
        return super(ThemeView,self).add(request,id)

    #移动主题
    def theme_move(self,request,id='0'):
        theme=models.BbsTheme.objects.get(id=id)
        dict={}
        dict['instance']=theme
        if request.method=="POST":
            classId=request.POST.get('bbsClass','')
            if classId!='':
                oldId=theme.classId.id
                newBbsClass=models.BbsClass.objects.get(id=classId)

                #replyList=models.BbsReply.objects.filter(theme=theme)
                #for reply in replyList:
                #    reply.classId=newBbsClass
                #    reply.save()
                #更新数据

                theme.classId.themeCount-=1
                theme.classId.replyCount-=theme.replyCount
                theme.classId.save()

                newBbsClass.themeCount+=1
                newBbsClass.replyCount+=theme.replyCount
                newBbsClass.save()

                theme.classId=newBbsClass
                theme.save()
                return super(ThemeView,self).showUrl('/BbsTheme/bbsTheme_list-%s/'%oldId)
            else:
                return HttpWrite.infoFailure(request,u'选择移动到的板块')
        else:
            dict['form']=forms.BbsClassSelectForm
        return render_to_response('BbsTheme/theme_move.html',dict, context_instance=RequestContext(request))


class ReplyView(ViewHelper):
    def __init__(self):
        self.moduleName='BbsTheme'
        self.typeName='reply'
    def get_model(self):
        return models.BbsReply
    def get_reply_form(self):
        import forms
        return forms.bbsReplyForm
    def list_get_list(self,request):
        #回复所在主题
        #bbsTheme=models.BbsTheme.objects.get(id=self.themeId)
        #回复列表
        list=models.BbsReply.objects_show.filter(theme=self.bbsTheme)
        #raise Exception,len(list)
        #self.bbsTheme=selfbbsTheme
        #return {}
        return list
    def list_get_dict(self,request):
        #wxj=getWxjHtml(self.bbsTheme.classId)
        return {'themeModel':self.bbsTheme,'replyForm':self.get_reply_form()}
    def list(self,request,themeId):
        self.themeId=themeId
        self.bbsTheme=models.BbsTheme.objects.get(id=self.themeId)
        if not VisitBbsClass(request.user,self.bbsTheme.classId):
            return HttpWrite.infoFailure(request,'不存在的主题')
        return super(ReplyView,self).list(request)

    def delete(self,request,id=''):
        instance=self.get_model().objects.get(id=id)
        instance.isDel=True
        instance.save()
        instance.theme.replyCount-=1
        instance.theme.save()
        #删除积分
        addReply_Extcredit(request,instance.addUser,'del')
        return super(ReplyView,self).showUrlReverse('bbsReply_list',args=(instance.theme.id,))
